import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:wallpaper/model/options_base.dart';

class SearchPixiv2 extends StatefulWidget {
  final String tag;
  final bool change;
  const SearchPixiv2({super.key, required this.tag, required this.change});

  @override
  State<SearchPixiv2> createState() => _SearchImageState();
}

class _SearchImageState extends State<SearchPixiv2>
    with AutomaticKeepAliveClientMixin {
  ScrollController scrollController = ScrollController();
  // 文本控制器
  List<ImageBase> pixivs = [];
  Set<String> results = <String>{};
  bool isLoading = false;
  late SharedPreferences prefs;

  void getR18() async {
    prefs = await SharedPreferences.getInstance();
    if (widget.tag.isNotEmpty) getData();
  }

  void getData() async {
    if (!mounted) return;

    setState(() {
      isLoading = true;
    });
    try {
      Response res =
          await getPixiv2(tag: widget.tag, r18: prefs.getInt('r18') ?? 0);
      List pics = res.data['data'];
      for (var i = 0; i < pics.length; i++) {
        ImageBase image = ImageBase(
          largePath: pics[i]['urls']['original'],
          smallPath: pics[i]['urls']['small'],
          tags: (pics[i]['tags'] as List<dynamic>?)?.join(' ') ?? '',
        );
        if (!results.contains(image.largePath)) {
          setState(() {
            pixivs.add(image);
            results.add(image.largePath);
          });
        }
      }
    } catch (e) {
      BotToast.showText(text: '获取失败');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    getR18();
    // 监听滚动 加载更多
    scrollController.addListener(() {
      if (isLoading) return;
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getData();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  // 监听 change 变化
  @override
  void didUpdateWidget(covariant SearchPixiv2 oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.change != widget.change) {
      setState(() {
        pixivs = [];
        results = <String>{};
      });
      getData();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('搜索图片'),
        toolbarHeight: 0,
        elevation: 0,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
      ),
      body: RefreshIndicator(
        onRefresh: () {
          setState(() {
            pixivs = [];
            results = <String>{};
          });
          getData();
          return Future.delayed(const Duration(milliseconds: 500));
        },
        child: CustomScrollView(
          controller: scrollController,
          slivers: [
            if (isLoading && pixivs.isEmpty)
              SliverToBoxAdapter(
                child: SizedBox(
                  // 屏幕高度
                  height: MediaQuery.of(context).size.height - 80,
                  child: Center(child: CircularProgressIndicator()),
                ),
              ),
            if (!isLoading && pixivs.isEmpty)
              SliverToBoxAdapter(child: Empty()),
            SliverGrid.builder(
              itemCount: pixivs.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: OptionsBase().imageColumns(context),
                childAspectRatio: 0.7,
              ),
              itemBuilder: (context, index) {
                return buildItem(context, index);
              },
            ),
            if (pixivs.isNotEmpty)
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(3.0),
                  child: SizedBox(
                    height: 30,
                    child: Center(
                      child: isLoading
                          ? MyLoading(
                              type: 1,
                              size: 30,
                            )
                          : Text('触底加载更多'),
                    ),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ImageView(
                          images: pixivs,
                          selectedIndex: index,
                          resetGetdata: () {},
                        )));
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ImageLoad(imageUrl: pixivs[index].smallPath)),
            Container(
                color: const Color.fromARGB(24, 158, 158, 158),
                width: double.infinity,
                height: pixivs[index].tags == "" ? 0 : 20,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: Text(
                    pixivs[index].tags,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                )),
          ]),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
